"""Setup the pubservices application"""
import logging
from datetime import date

import pylons.test
from pylons.i18n import lazy_ugettext as _

from chowa.lib.site.auth import add_permissions, add_groups
from chowa.lib.site.settings import add_options

from pubservices.config.environment import load_environment
from pubservices.model.meta import Session, Base

log = logging.getLogger(__name__)

def setup_app(command, conf, vars):
    """Place any commands to setup pubservices here"""
    # Don't reload the app if it was loaded under the testing environment
    if not pylons.test.pylonsapp:
        load_environment(conf.global_conf, conf.local_conf)

    # Create the tables if they don't already exist
    Base.metadata.create_all(bind=Session.bind)
    
    # Add permissions and groups
    admin_perms = [
        'pubservices.administer.settings',
        'pubservices.administer.records']
    clerk_perms = [
        'pubservices.add.record',
        'pubservices.edit.record']
    
    add_permissions(admin_perms + clerk_perms, Session)
    add_groups([
        ('pubservices.administrators', admin_perms),
        ('pubservices.clerks', clerk_perms),
    ], Session)
    
    today = date.today()
    add_options([
        ('read_only', 'group', _('Forbid data changes'), None),
        ('read_only.current', 'boolean', _('Current'), False),
        ('read_only.previous', 'boolean', _('Previous'), False),
        ('current_period', 'group', _('Current period'), None),
        ('current_period.year', 'integer', _('Year'), today.year),
        ('current_period.month', 'month', _('Month'), today.month),
    ], Session, prefix='pubservices')
